<?php
class JRecentManager extends CApplicationComponent {

	const KEY_PREFIX = 'recent.manager_';

	public $historyLength = 10;
	public $expire = 2419200;

	protected function getCache() {
		return Yii::app()->cache;
	}

	protected function getUserId() {
		return Yii::app()->user->id;
	}

	protected function createKey($name) {
		return self::KEY_PREFIX . $this->getUserId() . '_' . $name;
	}

	protected function normalize($component, $data) {
		if (is_string($component)) {
			$key = $this->createKey($component);
		} elseif (is_a($component, 'CActiveRecord')) {
			$key = $this->createKey(get_class($component));
			$data = $component->getPrimaryKey();
		} else {
			throw new CHttpException(500, 'Add unknown data to recent.');
		}
		return array(
			$key,
			$data
		);
	}

	public function add($component, $data = null) {
		list($key, $data) = $this->normalize($component, $data);
		$value = null;
		if ($value = $this->getCache()->get($key)) {
			if (in_array($data, $value)) {
				$newValue = array(
					$data
				);
				foreach ($value as $v) {
					if ($v != $data) {
						$newValue[] = $v;
					}
				}
				$value = $newValue;
			} else {
				array_unshift($value, $data);
			}
		} else {
			$value = array(
				$data
			);
		}
		if (count($value) > $this->historyLength) {
			$value = array_slice($value, 0, $this->historyLength, true);
		}
		$this->getCache()->set($key, $value, $this->expire);
	}

	public function clear($component) {
		list($key, $data) = $this->normalize($component, null);
		$this->getCache()->delete($key);
	}

	public function get($component, $length=null) {
		list($key, $data) = $this->normalize($component, null);
		if($length!==null){
			return array_slice($this->getCache()->get($key), 0, $length, true);
		}else{
			return $this->getCache()->get($key);
		}
	}
}
